var express = require('express');
const accountModel = require('../../modules/accountModel');
const dayjs = require('dayjs')
var customParseFormat = require('dayjs/plugin/customParseFormat')


var router = express.Router();

/* GET home page. */
router.get('/', function (req, res, next) {
  res.render('index', {
    title: 'Express'
  });
});
router.get('/account', (req, res, next) => {
  accountModel.find().sort({
    time: -1
  }).lean().exec().then(data => {
    data.forEach(item => {
      let timestr = dayjs(new Date(item.time)).format('YYYY-MM-DD')
      item.time = timestr
    })
    res.render('showAccount', {
      accounts: data
    })
  }, err => console.log(err))
})
router.get('/account/create', (req, res, next) => {
  res.render('createAccount')
})
router.post('/account/create', (req, res, next) => {
  console.log(req.body)
  //添加到mongo中 
  dayjs.extend(customParseFormat)
  accountModel.create({
    ...req.body,
    time: dayjs(req.body.time).toDate()
  }).then((data) => {
    console.log(data)
  }, (err) => console.log(err))

  res.render('success', {
    message: '添加成功',
    link: '/account'
  })
})
router.get('/account/:id', (req, res, next) => {
  console.log(req.params.id)
  accountModel.deleteOne({
    _id: req.params.id
  }).then(data => {
    console.log('删除成功', data)
  }).catch(err => console.log(err))

  res.render('success', {
    message: '删除成功',
    link: '/account'
  })
})
module.exports = router;